# mwsim
import re, string
from registers import *
from instructions import *

# read instructions
asm_text = """
loop: adD16 w1, w3, w6
org 0x19
l: ;sdfjoie
loop2:
subb64 u0, u3
call loop;wejoiwej;
"""





#print instrs
class Msim(Instructions):
    def __init__(self, asm_text):
        #self.instrs = instrs
        self.grs = GRs()
        
        Instructions.__init__(self, self.grs)
        self.addr = 0
        self.labels = {}
        self.imem = {}
        self.asm_text = asm_text
        
    def proc_asm(self):
        p = re.compile("[a-zA-Z_][a-zA-Z0-9_]*[\s]*:")
        for inst in re.split('[\s]*\n[\s]*', self.asm_text):
            inst = re.split("[\s]*;", inst)[0]
            if inst != '':            
                # get label
                m = p.match(inst)
                if m:
                    #print m.group()[:-1]
                    self.labels[m.group()[:-1]] = self.addr
                    inst = re.split(":[\s]*", inst)[1]
                # proc inst
                if inst != '':
                    [opcode, argvs, org_addr] = self.proc_inst(inst)
                    if org_addr != -1:
                        self.addr = org_addr
                    if opcode == -1:
                        return
                    # proc argvs
                    if self.instrs.has_key(opcode):
                        self.imem[self.addr] = [opcode, argvs]
                        self.addr = self.addr + 1
                        

                        
    def proc_inst(self, inst):
        [opcode, argvs] = re.split("[\s]*", inst, 1)

        opcode = opcode.lower()
                    
        #print "opcode:" ,opcode
        argvs = re.split('[\s]*,[\s]*', argvs)
        #print argvs
        
        org_addr = -1
        try:
            if opcode == 'org':
                if len(argvs[0]) > 1 and (argvs[0][1] in ['x', 'X'])                                                          :
                    org_addr = string.atoi(argvs[0], 16)
                else:
                    org_addr = string.atoi(argvs[0], 10)
        except:
            print "Format Error: Org"
            return [-1, -1, -1]
            
        return [opcode, argvs, org_addr]

    def list_asm(self):
        for i in self.imem.keys():
            print "%08X: %-10s" % (i, self.imem[i][0]),
            for j in self.imem[i][1]:
                print "%s " % j,
            print





                

                


            




#print instructions['add16'][2](['23', 3, 3, 't'])
pp = Msim(asm_text)
pp.proc_asm()
print pp.labels   
pp.list_asm()
pp.add16(['w3', 'w2', 'w1'])
